<?php
namespace common\models;

use Yii;
use common\component\tool\Tool;

class OperationLog extends \yii\db\ActiveRecord
{

    public static function getDb()
    {
        return Yii::$app->get("common_db");
    }
    
    public static function tableName()
    {
        return '{{%operation_log}}';
    }

    public function rules()
    {
        return [
            ['loginid', 'default', 'value' => 0],
            ['loginid', 'integer', 'message' => 'loginid必须为数字，或数字字符串', 
                     'min'=>0, 'tooSmall' => 'loginid最小存储0', 
                     'max'=>18446744073709551615, 'tooBig' => 'loginid最大存储18446744073709551615'],
            ['loginflag', 'default', 'value' => 1],
            ['loginflag', 'integer', 'message' => 'loginflag必须为数字，或数字字符串'],
            ['loginflag', 'in', 'range' => array(1, 2), 'message' => 'loginflag值必须在1,2中才选择'],
            ['loginname', 'default', 'value' => ''],
            ['loginname', 'string', 'message' => 'loginname必须是字符串', 
                          'max' => 32, 'tooLong' => 'loginname最长32位'],
            ['back_code', 'default', 'value' => ''],
            ['back_code', 'string', 'message' => 'back_code必须是字符串', 
                          'max' => 8, 'tooLong' => 'back_code最长8位'],
            ['back_info', 'default', 'value' => ''],
            ['back_info', 'string', 'message' => 'back_info必须是字符串'],
            ['appid', 'default', 'value' => ''],
            ['appid', 'string', 'message' => 'appid必须是字符串', 
                      'max' => 18, 'tooLong' => 'appid最长18位'],
            ['comid', 'default', 'value' => ''],
            ['comid', 'string', 'message' => 'comid必须是字符串', 
                      'max' => 8, 'tooLong' => 'comid最长8位'],
            ['status_code', 'default', 'value' => ''],
            ['status_code', 'string', 'message' => 'status_code必须是字符串', 
                            'max' => 16, 'tooLong' => 'status_code最长16位'],
            ['obj_class', 'default', 'value' => ''],
            ['obj_class', 'string', 'message' => 'obj_class必须是字符串', 
                          'max' => 256, 'tooLong' => 'obj_class最长256位'],
            ['message', 'default', 'value' => ''],
            ['message', 'string', 'message' => 'message必须是字符串', 
                        'max' => 8192, 'tooLong' => 'message最长8192位'],
            ['file', 'default', 'value' => ''],
            ['file', 'string', 'message' => 'file必须是字符串', 
                     'max' => 256, 'tooLong' => 'file最长256位'],
            ['line', 'default', 'value' => 0],
            ['line', 'integer', 'message' => 'line必须为数字，或数字字符串', 
                     'min'=>0, 'tooSmall' => 'line最小存储0', 
                     'max'=>4294967295, 'tooBig' => 'line最大存储4294967295'],
            ['model_error', 'default', 'value' => ''],
            ['model_error', 'string', 'message' => 'model_error必须是字符串'],
            ['url', 'default', 'value' => ''],
            ['url', 'string', 'message' => 'url必须是字符串', 
                    'max' => 256, 'tooLong' => 'url最长256位'],
            ['get_args', 'default', 'value' => ''],
            ['get_args', 'string', 'message' => 'get_args必须是字符串'],
            ['post_args', 'default', 'value' => ''],
            ['post_args', 'string', 'message' => 'post_args必须是字符串'],
            ['cookies', 'default', 'value' => ''],
            ['cookies', 'string', 'message' => 'cookies必须是字符串'],
            ['session', 'default', 'value' => ''],
            ['session', 'string', 'message' => 'session必须是字符串'],
            ['request_way', 'default', 'value' => 1],
            ['request_way', 'integer', 'message' => 'request_way必须为数字，或数字字符串'],
            ['request_way', 'in', 'range' => array(1, 2, 3), 'message' => 'request_way值必须在1,2,3中才选择'],
            ['state', 'default', 'value' => 1],
            ['state', 'integer', 'message' => 'state必须为数字，或数字字符串'],
            ['state', 'in', 'range' => array(1, 2, 3, 4), 'message' => 'state值必须在1,2,3,4中才选择'],
            ['ip_addr', 'default', 'value' => ''],
            ['ip_addr', 'string', 'message' => 'ip_addr必须是字符串', 
                        'max' => 512, 'tooLong' => 'ip_addr最长512位'],
            ['ip', 'string', 'message' => 'ip必须是字符串', 
                            'max' => 64, 'tooLong' => 'ip最长64位'], 
            ['browser', 'default', 'value' => ''],
            ['browser', 'string', 'message' => 'browser必须是字符串', 
                        'max' => 512, 'tooLong' => 'browser最长512位'],
            ['solve_time', 'default', 'value' => '1000-01-01 00:00:00'],
            ['solve_time', 'date', 'format'=>'yyyy-MM-dd HH:mm:ss', 'message' => 'solve_time非yyyy-MM-dd HH:mm:ss格式'],
            ['add_time', 'default', 'value' => '1000-01-01 00:00:00'],
            ['add_time', 'date', 'format'=>'yyyy-MM-dd HH:mm:ss', 'message' => 'add_time非yyyy-MM-dd HH:mm:ss格式'],
        ];
    }

    /*
    添加日志
    $args = array{
        'loginid'           登录ID
        'loginflag'         用户标识 1-后台登录2-前台登录
        'loginname'         用户名
        'back_code'         返回码
        'back_info'         返回信息
        'appid'             子应用ID
        'comid'             企业ID
    }
    $exception      异常信息 如果类型为object 说明是捕捉的错误异常，如果是array说明是模型验证错误
    $backInfo       true-输出返回值 false-不输出
    $backData       返回值
    $hasBack        是否需要返回值
    */
    public static function addLog($args, $exception = '', $backData='', $hasBack = true)
    {
        if(session_status() != 2){
            session_start();
        };
        $url = Yii::$app->request->hostInfo . Yii::$app->request->getUrl();//当前完整URL
        $get = Yii::$app->request->get();
        $post = Yii::$app->request->post();
        $requestWay = 1;

        if(Yii::$app->request->isGet){
            $requestWay = 2;
        }

        if(Yii::$app->request->isPost){
            $requestWay = 3;
        }

        if(!isset($args['loginflag'])){
            $args['loginflag'] = Yii::$app->params['loginflag']['backend'];
        }

        $back_code = (string)(isset($args['back_code'])?$args['back_code']:0);//返回码
        $back_info = isset($args['back_info'])?$args['back_info']:'';//返回信息

        $status_code = '';//错误码 比如404
        $obj_class = '';//错误的实例名
        $message = '';//错误消息
        $file = '';//错误文件
        $line = '';//错误行
        if(!empty($exception) and gettype($exception) == 'object'){//捕捉的错误异常
            $status_code = (string)(isset($exception->statusCode) ? $exception->statusCode : $exception->getCode());//错误码 比如404
            $obj_class = get_class($exception);//错误的实例名
            $message = $exception->getMessage();//错误消息
            $file = $exception->getFile();//错误文件
            $line = $exception->getLine();//错误行
        }
        if(!empty($exception) and gettype($exception) == 'array'){//模型验证错误
            $modelError = json_encode($exception);
        }
        $data = array(
            'loginid' => isset($args['loginid'])?$args['loginid']:0,//登录ID
            'loginname' => isset($args['loginname'])?$args['loginname']:'',//操作登录名
            'back_code' => $back_code,//返回码
            'back_info' => $back_info,//返回信息
            'appid' => isset($args['appid'])?$args['appid']:'',//返回信息
            'comid' => isset($args['comid'])?$args['comid']:'',//返回信息
            ###如果有错误，记录错误信息
            'status_code' => $status_code,//错误码 比如404
            'obj_class' => $obj_class,//错误的实例名
            'message' => $message,//错误消息
            'file' => $file,//错误文件
            'line' => $line,//错误行
            ###如果有错误，记录错误信息
            ###如果有错误，记录模型错误信息
            'model_error' => isset($modelError)?$modelError:'',//模型验证错误
            ###如果有错误，记录模型错误信息
            'url' => $url,//当前完整URL
            'get_args' => !empty($get)?json_encode($get):'',//发生错误时候，GET参数
            'post_args' => !empty($post)?json_encode($post):'',//发生错误时候，POST参数
            'cookies' => empty($_COOKIE)?json_encode($_COOKIE):'',//发生错误时候，cookies
            'session' => empty($_SESSION)?json_encode($_SESSION):'',//发生错误时候，session
            'request_way' => $requestWay,
            'state' => 1,
            'ip_addr' => '',
            'ip' => Yii::$app->request->userIP,
            'browser' => isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'',
            'solve_time' => '',
            'add_time' => date('Y-m-d H:i:s', time()),
        );


        $data = array(
            'OperationLog' => $data
        );
        // P($data);

        $operationLog = new OperationLog();
        if($operationLog->load($data) and $operationLog->validate()){
            if($operationLog->save(false)){
                if($hasBack){
                    return Tool::showRes([$back_code, $back_info], $backData);
                }
            }
        }else{
            if($operationLog->hasErrors()){
                echo 'operation_log';
                P($operationLog->getErrors());
                //写入错误日志

            }
        }
        return false;
    }



}
